package com.itheima.easy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.easy.base.AjaxResult;
import com.itheima.easy.base.PageResponse;
import com.itheima.easy.constant.AccraditationRecordConstant;
import com.itheima.easy.constant.PendingTasksConstant;
import com.itheima.easy.constant.RetreatConstant;
import com.itheima.easy.dto.CheckInDto;
import com.itheima.easy.entity.*;
import com.itheima.easy.enums.Applications;
import com.itheima.easy.mapper.*;
import com.itheima.easy.service.ApplicationsService;
import com.itheima.easy.service.CheckInService;
import com.itheima.easy.service.ElderService;
import com.itheima.easy.service.PendingTasksService;
import com.itheima.easy.utils.CodeUtil;
import com.itheima.easy.utils.UserThreadLocal;
import com.itheima.easy.vo.CheckInVo;
import com.itheima.easy.vo.retreat.ElderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CheckInServiceImpl implements CheckInService {

    @Resource
    private CheckInMapper checkInMapper;

    @Resource
    private ElderService elderService;

    @Resource
    private DeptPostUserMapper deptPostUserMapper;

    @Autowired
    private DeptMapper deptMapper;

    private static final String CHECK_IN_CODE_PREFIX = "RZ";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PendingTasksMapper pendingTasksMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private ApplicationsMapper applicationsMapper;

    @Resource
    private PendingTasksService pendingTasksService;


    @Autowired
    private ApplicationsService applicationsService;

    @Transactional
    @Override
    public AjaxResult<CheckInVo> createCheckIn(CheckInDto checkInDto) {
        //1.验证状态
        ElderVo elderVo = elderService.selectByIdCardAndName(checkInDto.getElderDto().getIdCardNo(), checkInDto.getElderDto().getName());
        if (elderVo != null) {
            return AjaxResult.error(checkInDto.getElderDto().getName() + "已经发起了申请入住");
        }
        CheckIn checkIn = BeanUtil.toBean(checkInDto, CheckIn.class);
        Elder elder = elderService.insert(checkIn.getElderDto());
        checkIn.setElderId(elder.getId());

        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);

        //找到申请人部门，通过部门找到对应的负责人
        List<DeptPostUser> deptPostUserList = deptPostUserMapper.findDeptPostUserByUserId(user.getId());
        DeptPostUser deptPostUser = deptPostUserList.get(0);
        //申请人部门编号
        String deptNo = deptPostUser.getDeptNo();

        //设置流程状态
        checkIn.setFlowStatus(CheckIn.FlowStatus.APPLY.getCode());
        checkIn.setStatus(CheckIn.Status.APPLICATION.getCode());
        if (checkIn.getCheckInCode() != null) {
            if (!user.getId().equals(checkIn.getApplicatId())) {
                return AjaxResult.error("不是申请人，不能提交数据");
            }
            checkInMapper.updateByPrimaryKeySelective(checkIn);
        } else {
            checkIn.setApplicat(user.getRealName());
            checkIn.setApplicatId(user.getId());
            //创建时间
            checkIn.setCreateTime(LocalDateTime.now());
            //退住标题
            String title = elder.getName() + "的入住申请";
            checkIn.setTitle(title);
            checkIn.setStatus(Retreat.Status.APPLICATION.getCode());
            //设置下个操作人
            String code = CodeUtil.generateCode(CHECK_IN_CODE_PREFIX, redisTemplate, 5);
            checkIn.setCheckInCode(code);
            checkIn.setDeptNo(deptNo);
            checkIn.setCounselor(user.getRealName());
            //设置下一个状态
            checkInMapper.insert(checkIn);

            //保存我的申请
            Applications applications = new Applications();
            applications.setApplicat(user.getRealName());
            applications.setApplicationTime(checkIn.getCheckOutTime());
            applications.setApplicatId(user.getId());
            applications.setCode(code);
            applications.setStatus(CheckIn.Status.APPLICATION.getCode());
            applications.setTitle(title);
            applications.setType(PendingTasksConstant.TASK_TYPE_CHECK_IN);
            applicationsMapper.insert(applications);
        }
        //记录操作记录
        // 护理部部门编号
        String nDeptNo = "100001008000000";
        Dept dept = deptMapper.selectByDeptNo(nDeptNo);
        //部门领导id
        Long leaderId = dept.getLeaderId();
        applicationsService.insert(leaderId, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_PASS, "同意");
//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion("同意");
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_PASS);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());

//        // 护理部部门编号
//        String nDeptNo = "100001008000000";
//        Dept dept = deptMapper.selectByDeptNo(nDeptNo);
//        //部门领导id
//        Long leaderId = dept.getLeaderId();

//        //查询下一个审核人的姓名和角色
//        List<UserRoleVo> userRoleVoList = userRoleMapper.selectByUserId(leaderId);
//        //待办任务，下个节点审核人 设置下个操作人--->护理部主管
//        UserRoleVo userRoleVo = userRoleVoList.get(0);

//        //审核记录，设置下个节点审核人的角色和用户名
//        accraditationRecord.setNextApprover(userRoleVo.getUserName());
//        List<String> roleNameList = userRoleVoList.stream().map(x -> x.getRoleName()).collect(Collectors.toList());
//        accraditationRecord.setNextApproverRole(StringUtils.join(roleNameList, ","));
//        accraditationRecord.setNextApproverId(userRoleVo.getId());
//        //保存审核（操作）记录
//        accraditationRecordMapper.insert(accraditationRecord);

        //设置待办
        pendingTasksService.insert(leaderId, checkIn, CheckIn.FlowStatus.REVIEW.getCode());
        return AjaxResult.success(BeanUtil.toBean(checkIn, CheckInVo.class));
    }



    /**
     * 封装待办对象
     *
     * @param checkIn
     * @param accraditationStepNoOne
     * @return
     */


    /**
     * 查询入住信息
     * @param      * @param status
     * @param id
     * @return
     */
    @Override
    public AjaxResult<CheckInVo> getCheckIn(Long id, String assigneeId, Integer flowStatus) {
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(id);
        CheckInVo checkInVo = BeanUtil.toBean(checkIn, CheckInVo.class);
        ElderVo elderVo = elderService.selectByPrimaryKey(checkIn.getElderId());
        checkInVo.setElderVo(elderVo);
        return AjaxResult.success(checkInVo);
    }

    /**
     * 同意入住申请
     * @param checkInDto
     * @return
     */
    @Override
    public AjaxResult<CheckInVo> submitCheckIn(CheckInDto checkInDto) {
        // 流程状态 操作记录
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(checkInDto.getId());
        //设置流程状态
        checkIn.setFlowStatus(CheckIn.FlowStatus.APPROVAL.getCode());
        checkInMapper.updateByPrimaryKeySelective(checkIn);
        //  操作记录
        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        //修改之前的待办任务状态，为已处理
        pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_FINISHED, user.getId());

        //记录操作记录
        // 养老顾问
        CheckIn checkIn1 = checkInMapper.selectByPrimaryKey(checkIn.getId());
        Long userId = checkIn1.getApplicatId();
        applicationsService.insert(userId, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_PASS, "同意");
//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion("同意");
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_PASS);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());
//
//        // 养老顾问
//        CheckIn checkIn1 = checkInMapper.selectByPrimaryKey(checkIn.getId());
//        Long userId = checkIn1.getApplicatId();
//        //查询下一个审核人的姓名和角色
//        List<UserRoleVo> userRoleVoList = userRoleMapper.selectByUserId(userId);
//        //待办任务，下个节点审核人 设置下个操作人--->护理部主管
//        UserRoleVo userRoleVo = userRoleVoList.get(0);
//
//        //审核记录，设置下个节点审核人的角色和用户名
//        accraditationRecord.setNextApprover(userRoleVo.getUserName());
//        List<String> roleNameList = userRoleVoList.stream().map(x -> x.getRoleName()).collect(Collectors.toList());
//        accraditationRecord.setNextApproverRole(StringUtils.join(roleNameList, ","));
//        accraditationRecord.setNextApproverId(userRoleVo.getId());
//        //保存审核（操作）记录
//        accraditationRecordMapper.insert(accraditationRecord);

        //设置待办
        pendingTasksService.insert(userId, checkIn, CheckIn.FlowStatus.CONFIG.getCode());
//        PendingTasks pendingTasks = pendingTasksMapper.selectByCodeAndAssinessId(checkIn.getCheckInCode(), userRoleVo.getId());
//        if (pendingTasks != null) {
//            pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_UNTREATED, userRoleVo.getId());
//        } else {
//            pendingTasks = getPendingTasks(checkIn, );
//            pendingTasks.setAssignee(userRoleVo.getUserName());
//            pendingTasks.setAssigneeId(userRoleVo.getId());
//            pendingTasksMapper.insert(pendingTasks);
//        }
        return AjaxResult.success(BeanUtil.toBean(checkIn, CheckInVo.class));
    }

    /**
     * 审核拒绝
     * @param id  入住单code
     * @param reject   拒绝原因
     * @return
     */
    @Override
    public AjaxResult<CheckInVo> auditReject(Long id, String reject) {
        // 流程状态 操作记录
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(id);
        //设置流程状态
        checkIn.setFlowStatus(CheckIn.FlowStatus.APPROVAL.getCode());
        checkIn.setStatus(CheckIn.Status.CLOSED.getCode());
        checkInMapper.updateByPrimaryKeySelective(checkIn);

        applicationsMapper.updateStatus(checkIn.getCheckInCode(), LocalDateTime.now(), CheckIn.Status.CLOSED.getCode());

        //  操作记录
        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        //修改之前的待办任务状态，为已处理
        pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_FINISHED, user.getId());

        //记录操作记录
        applicationsService.insert(null, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_REJECT, reject);
//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion(reject);
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_REJECT);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());

        // 删除老人数据
        elderService.deleteByPrimaryKey(checkIn.getElderId());
        return AjaxResult.success(BeanUtil.toBean(checkIn, CheckInVo.class));
    }

    /**
     * 撤回
     * @param id
     * @param flowStatus
     * @return
     */
    @Override
    public AjaxResult<CheckInVo> revocation(Long id, Integer flowStatus) {
        // 流程状态 操作记录
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(id);
        //设置流程状态
        checkIn.setFlowStatus(flowStatus);
        checkInMapper.updateByPrimaryKeySelective(checkIn);
        //  操作记录
        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        //修改之前的待办任务状态，为已处理
        pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_FINISHED, user.getId());

        //记录操作记录
        // 护理部部门编号
        String nDeptNo = "100001008000000";
        Dept dept = deptMapper.selectByDeptNo(nDeptNo);
        //部门领导id
        Long leaderId = dept.getLeaderId();
        applicationsService.insert(leaderId, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_WITHDRAWS, "撤回");

//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion("撤回");
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_WITHDRAWS);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());
//
//        // 护理部部门编号
//        String nDeptNo = "100001008000000";
//        Dept dept = deptMapper.selectByDeptNo(nDeptNo);
//        //部门领导id
//        Long leaderId = dept.getLeaderId();
        //查询下一个审核人的姓名和角色
//        List<UserRoleVo> userRoleVoList = userRoleMapper.selectByUserId(leaderId);
//        //待办任务，下个节点审核人 设置下个操作人--->护理部主管
//        UserRoleVo userRoleVo = userRoleVoList.get(0);
//
//        //审核记录，设置下个节点审核人的角色和用户名
//        accraditationRecord.setNextApprover(userRoleVo.getUserName());
//        List<String> roleNameList = userRoleVoList.stream().map(x -> x.getRoleName()).collect(Collectors.toList());
//        accraditationRecord.setNextApproverRole(StringUtils.join(roleNameList, ","));
//        accraditationRecord.setNextApproverId(userRoleVo.getId());
//        //保存审核（操作）记录
//        accraditationRecordMapper.insert(accraditationRecord);

        //设置待办
        pendingTasksService.insert(leaderId, checkIn, flowStatus);
//        PendingTasks pendingTasks = pendingTasksMapper.selectByCodeAndAssinessId(checkIn.getCheckInCode(), userRoleVo.getId());
//        if (pendingTasks != null) {
//            pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_UNTREATED, userRoleVo.getId());
//        } else {
//            pendingTasks = getPendingTasks(checkIn, flowStatus);
//            pendingTasks.setAssignee(userRoleVo.getUserName());
//            pendingTasks.setAssigneeId(userRoleVo.getId());
//            pendingTasksMapper.insert(pendingTasks);
//        }
        return AjaxResult.success(BeanUtil.toBean(checkIn, CheckInVo.class));
    }

    /**
     * 撤销驳回
     * @param id
     * @return
     */
    @Override
    public AjaxResult<CheckInVo> disapprove(Long id, String message) {
        // 流程状态 操作记录
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(id);
        //设置流程状态
        checkIn.setFlowStatus(CheckIn.FlowStatus.REVIEW.getCode());
        checkInMapper.updateByPrimaryKeySelective(checkIn);
        //  操作记录
        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        //修改之前的待办任务状态，为已处理
        pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_FINISHED, user.getId());

        //记录操作记录
        String nDeptNo = "100001008000000";
        Dept dept = deptMapper.selectByDeptNo(nDeptNo);
        //部门领导id
        Long leaderId = dept.getLeaderId();
        applicationsService.insert(leaderId, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_DISAPPROVE, message);
//
//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion(message);
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_DISAPPROVE);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());
//
//        // 护理部部门编号
//        String nDeptNo = "100001008000000";
//        Dept dept = deptMapper.selectByDeptNo(nDeptNo);
//        //部门领导id
//        Long leaderId = dept.getLeaderId();
//        //查询下一个审核人的姓名和角色
//        List<UserRoleVo> userRoleVoList = userRoleMapper.selectByUserId(leaderId);
//        //待办任务，下个节点审核人 设置下个操作人--->护理部主管
//        UserRoleVo userRoleVo = userRoleVoList.get(0);
//
//        //审核记录，设置下个节点审核人的角色和用户名
//        accraditationRecord.setNextApprover(userRoleVo.getUserName());
//        List<String> roleNameList = userRoleVoList.stream().map(x -> x.getRoleName()).collect(Collectors.toList());
//        accraditationRecord.setNextApproverRole(StringUtils.join(roleNameList, ","));
//        accraditationRecord.setNextApproverId(userRoleVo.getId());
//        //保存审核（操作）记录
//        accraditationRecordMapper.insert(accraditationRecord);

        //设置待办
        pendingTasksService.insert(leaderId, checkIn, CheckIn.FlowStatus.REVIEW.getCode());
//        PendingTasks pendingTasks = pendingTasksMapper.selectByCodeAndAssinessId(checkIn.getCheckInCode(), userRoleVo.getId());
//        if (pendingTasks != null) {
//            pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_UNTREATED, userRoleVo.getId());
//        } else {
//            pendingTasks = getPendingTasks(checkIn, CheckIn.FlowStatus.REVIEW.getCode());
//            pendingTasks.setAssignee(userRoleVo.getUserName());
//            pendingTasks.setAssigneeId(userRoleVo.getId());
//            pendingTasksMapper.insert(pendingTasks);
//        }
        return AjaxResult.success(BeanUtil.toBean(checkIn, CheckInVo.class));
    }

    @Override
    public AjaxResult<PageResponse<CheckInVo>> selectByPage(String checkInCode, String name, String idCardNo, LocalDateTime start, LocalDateTime end, Integer pageNum, Integer pageSize, String deptNo, Long userId) {
        PageHelper.startPage(pageNum, pageSize);
        Page<List<CheckIn>> lists = checkInMapper.selectByPage(checkInCode, name, idCardNo, start, end, userId, deptNo);
        return AjaxResult.success(PageResponse.of(lists, CheckInVo.class));
    }

    /**
     * 撤销
     * @param id  入住编码
     * @return
     */
    @Override
    public AjaxResult<CheckInVo> cancel(Long id) {
        // 流程状态 操作记录
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(id);
        //设置流程状态
        checkIn.setFlowStatus(CheckIn.FlowStatus.APPLY.getCode());
        checkIn.setStatus(CheckIn.Status.CLOSED.getCode());
        checkInMapper.updateByPrimaryKeySelective(checkIn);

        applicationsMapper.updateStatus(checkIn.getCheckInCode(), LocalDateTime.now(), CheckIn.Status.CLOSED.getCode());

        //  操作记录
        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        //修改之前的待办任务状态，为已处理
        pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_FINISHED, user.getId());

        //记录操作记录
        applicationsService.insert(null, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_CANCEL, "撤销");
//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion("撤销");
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_CANCEL);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());
        return AjaxResult.success(BeanUtil.toBean(checkIn, CheckInVo.class));
    }

    @Transactional
    @Override
    public AjaxResult<CheckInVo> review(CheckInDto checkInDto) {
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(checkInDto.getId());
        //设置流程状态
        checkIn.setFlowStatus(CheckIn.FlowStatus.REVIEW.getCode());
        checkInMapper.updateByPrimaryKeySelective(checkIn);
        //  操作记录
        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);

        //修改之前的待办任务状态，为已处理
        pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_FINISHED, user.getId());

        //记录操作记录
        //设置下一个审核人--寻找副院长
        //找到法务部门编号--->通过编号查询法务中所有的员工（非leader）---->获取第一个人，找到这个人的id,然后查询对应的角色
        List<Long> userIdList = deptPostUserMapper.selectByDeptNo(RetreatConstant.DEAN_OFFICE_DEPT_CODE);
        Long userId = userIdList.get(0);

        applicationsService.insert(userId, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_PASS, "同意");
//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion("同意");
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_PASS);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());
//
//        //设置下一个审核人--寻找副院长
//        //找到法务部门编号--->通过编号查询法务中所有的员工（非leader）---->获取第一个人，找到这个人的id,然后查询对应的角色
//        List<Long> userIdList = deptPostUserMapper.selectByDeptNo(RetreatConstant.DEAN_OFFICE_DEPT_CODE);
//        Long userId = userIdList.get(0);
//
//        //查询下一个审核人的姓名和角色
//        List<UserRoleVo> userRoleVoList = userRoleMapper.selectByUserId(userId);
//        //待办任务，下个节点审核人 设置下个操作人--->护理部主管
//        UserRoleVo userRoleVo = userRoleVoList.get(0);
//
//        //审核记录，设置下个节点审核人的角色和用户名
//        accraditationRecord.setNextApprover(userRoleVo.getUserName());
//        List<String> roleNameList = userRoleVoList.stream().map(x -> x.getRoleName()).collect(Collectors.toList());
//        accraditationRecord.setNextApproverRole(StringUtils.join(roleNameList, ","));
//        accraditationRecord.setNextApproverId(userRoleVo.getId());
//        //保存审核（操作）记录
//        accraditationRecordMapper.insert(accraditationRecord);

        //设置待办
        pendingTasksService.insert(userId, checkIn, CheckIn.FlowStatus.APPROVAL.getCode());
//        PendingTasks pendingTasks = pendingTasksMapper.selectByCodeAndAssinessId(checkIn.getCheckInCode(), userRoleVo.getId());
//        if (pendingTasks != null) {
//            pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_UNTREATED, userRoleVo.getId());
//        } else {
//            pendingTasks = getPendingTasks(checkIn, CheckIn.FlowStatus.APPROVAL.getCode());
//            pendingTasks.setAssignee(userRoleVo.getUserName());
//            pendingTasks.setAssigneeId(userRoleVo.getId());
//            pendingTasksMapper.insert(pendingTasks);
//        }
        return AjaxResult.success(BeanUtil.toBean(checkIn, CheckInVo.class));
    }
}
